package com.java110.mall.chain.partner.adapter.hibo.utils;


import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {
    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager cm = null;
    private static SSLContextBuilder builder = null;

    static {
        try {
            builder = new SSLContextBuilder();
            builder.loadTrustMaterial((KeyStore)null, (x509Certificates, s) -> {
                return true;
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, (String[])null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry =
                    RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http",  new PlainConnectionSocketFactory())
                            .register("https", sslsf)
                            .build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(1000);
            cm.setDefaultMaxPerRoute(200);
        } catch (Exception var1) {
            log.error("HttpClient 初始化失败: {}", var1.getMessage(), var1);
        }

    }

    public HttpUtils() {
    }

    public static HttpResponse get(String url) throws Exception {
        try {
            CloseableHttpClient httpClient = getHttpClient();
            Throwable var2 = null;

            CloseableHttpResponse var4;
            try {
                HttpGet httpGet = new HttpGet(url);
                var4 = httpClient.execute(httpGet);
            } catch (Throwable var14) {
                var2 = var14;
                throw var14;
            } finally {
                if (httpClient != null) {
                    if (var2 != null) {
                        try {
                            httpClient.close();
                        } catch (Throwable var13) {
                            var2.addSuppressed(var13);
                        }
                    } else {
                        httpClient.close();
                    }
                }

            }

            return var4;
        } catch (Exception var16) {
            log.error("HttpClient 发送get请求失败: {}", var16.getMessage(), var16);
            throw var16;
        }
    }

    public static String get(String url, Map<String, String> header, Map<String, String> param) throws Exception {
        String result = "";

        try {
            CloseableHttpClient httpClient = getHttpClient();
            Throwable var5 = null;

            try {
                HttpGet httpGet = new HttpGet(buildUrl(url, param));
                if (MapUtils.isNotEmpty(header)) {
                    Iterator var7 = header.entrySet().iterator();

                    while(var7.hasNext()) {
                        Map.Entry<String, String> entry = (Map.Entry)var7.next();
                        httpGet.addHeader((String)entry.getKey(), (String)entry.getValue());
                    }
                }

                HttpResponse httpResponse = httpClient.execute(httpGet);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity resEntity = httpResponse.getEntity();
                    result = EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
                } else {
                    readHttpResponse(httpResponse);
                }
            } catch (Throwable var18) {
                var5 = var18;
                throw var18;
            } finally {
                if (httpClient != null) {
                    if (var5 != null) {
                        try {
                            httpClient.close();
                        } catch (Throwable var17) {
                            var5.addSuppressed(var17);
                        }
                    } else {
                        httpClient.close();
                    }
                }

            }

            return result;
        } catch (Exception var20) {
            log.error("HttpClient 发送get请求失败: {}", var20.getMessage(), var20);
            throw var20;
        }
    }

    private static String buildUrl(String url, Map<String, String> querys) throws Exception {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            Iterator var4 = querys.entrySet().iterator();

            while(var4.hasNext()) {
                Map.Entry<String, String> query = (Map.Entry)var4.next();
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }

                if (StringUtils.isBlank((CharSequence)query.getKey()) && !StringUtils.isBlank((CharSequence)query.getValue())) {
                    sbQuery.append((String)query.getValue());
                }

                if (!StringUtils.isBlank((CharSequence)query.getKey())) {
                    sbQuery.append((String)query.getKey());
                    if (!StringUtils.isBlank((CharSequence)query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode((String)query.getValue(), StandardCharsets.UTF_8.name()));
                    }
                }
            }

            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    public static String postJson(String url, Map<String, String> param) throws Exception {
        String result = "";

        try {
            CloseableHttpClient httpClient = getHttpClient();
            Throwable var4 = null;

            try {
                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(4000).setConnectionRequestTimeout(1000).setSocketTimeout(4000).build();
                httpPost.setConfig(requestConfig);
                if (MapUtils.isNotEmpty(param)) {
                    StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(param), StandardCharsets.UTF_8);
                    httpPost.setEntity(stringEntity);
                }

                HttpResponse httpResponse = httpClient.execute(httpPost);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity resEntity = httpResponse.getEntity();
                    result = EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
                } else {
                    result = readHttpResponse(httpResponse);
                }
            } catch (Throwable var18) {
                var4 = var18;
                throw var18;
            } finally {
                if (httpClient != null) {
                    if (var4 != null) {
                        try {
                            httpClient.close();
                        } catch (Throwable var17) {
                            var4.addSuppressed(var17);
                        }
                    } else {
                        httpClient.close();
                    }
                }

            }

            return result;
        } catch (Exception var20) {
            log.error("HttpClient 发送post请求失败: {}", var20.getMessage(), var20);
            throw var20;
        }
    }

    public static HttpResponse post(String url, Map<String, ?> param) throws Exception {
        try {
            CloseableHttpClient httpClient = getHttpClient();
            Throwable var3 = null;

            CloseableHttpResponse var22;
            try {
                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
                RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(6000).build();
                httpPost.setConfig(requestConfig);
                if (MapUtils.isNotEmpty(param)) {
                    boolean emptyParams = null == param || param.isEmpty();
                    List<NameValuePair> nvps = new ArrayList(emptyParams ? 0 : param.size());
                    if (!emptyParams) {
                        Iterator i$ = param.entrySet().iterator();

                        while(i$.hasNext()) {
                            Map.Entry<String, ?> entry = (Map.Entry)i$.next();
                            Object val = entry.getValue();
                            nvps.add(new BasicNameValuePair((String)entry.getKey(), val != null ? val.toString() : ""));
                        }
                    }

                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8);
                    httpPost.setEntity(entity);
                }

                var22 = httpClient.execute(httpPost);
            } catch (Throwable var19) {
                var3 = var19;
                throw var19;
            } finally {
                if (httpClient != null) {
                    if (var3 != null) {
                        try {
                            httpClient.close();
                        } catch (Throwable var18) {
                            var3.addSuppressed(var18);
                        }
                    } else {
                        httpClient.close();
                    }
                }

            }

            return var22;
        } catch (Exception var21) {
            log.error("HttpClient 发送post请求失败: {}", var21.getMessage(), var21);
            throw var21;
        }
    }

    public static CloseableHttpClient getHttpClient() {
        return HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setConnectionManagerShared(true).build();
    }

    public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {
        StringBuilder builder = new StringBuilder();
        HttpEntity entity = httpResponse.getEntity();
        builder.append("status:").append(httpResponse.getStatusLine());
        builder.append("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();

        while(iterator.hasNext()) {
            builder.append("\t").append(iterator.next());
        }

        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            builder.append("response length:").append(responseString.length());
            builder.append("response content:").append(responseString.replace("\r\n", ""));
        }

        return builder.toString();
    }


}